import Device from 'react-native-device-info';
import {Platform} from 'react-native';
import * as RNLocalize from 'react-native-localize';
import Keychain from 'M/Utils/Keychain';
import uuid from 'react-native-uuid';

export default class DeviceInfo {
  /**
   * 设备ID
   * Android是直接获取的ANDROID_ID，卸载重装后不发生变化
   * @return {string}
   */
  constructor(isIOS = false) {
    this.isIOS = isIOS;
    const _this = this;
    Device.getDeviceName().then(value => (_this.deviceName = value));
    Device.getMacAddress().then(value => (_this.macAddress = value));
    (this.getUniqueID() || this.getIOSDeviceUID()).then(
      value => (_this.uniqueId = value),
    );
  }

  async getUniqueID() {
    if (this.isIOS) {
      return await this.getIOSDeviceUID();
    }
    return await Device.getUniqueId();
  }

  async getIOSDeviceUID() {
    if (!this.isIOS || this.iosDeviceUID) {
      return;
    }
    const uid = await Keychain.get('LocalDeviceUID');
    if (uid) {
      this.iosDeviceUID = uid;
    } else {
      const oldUid = await Keychain.get('deviceUID');
      this.iosDeviceUID = oldUid || uuid.v4();
      await Keychain.set('LocalDeviceUID', this.iosDeviceUID);
    }
  }

  getVersion() {
    // 1.48.2
    return Device.getVersion();
  }

  /**
   * 获取系统api级别，如Android 13的是33
   * @returns {Promise<number>}
   */
  getApiLevel() {
    return Device.getApiLevel();
  }

  getTimezone() {
    // Asia/Shanghai
    return RNLocalize.getTimeZone();
  }

  getDeviceLocale() {
    // zh-CN
    return RNLocalize.getLocales()[0].languageTag;
  }

  getDeviceInfo() {
    if (!this.cacheDeviceInfo) {
      this.cacheDeviceInfo = {
        'X-DEVICE-BRAND': Device.getBrand(),
        'X-DEVICE-ID': this.uniqueId,
        'X-DEVICE-MODEL': Device.getModel(),
        'X-DEVICE-NAME': this.deviceName,
        'X-DEVICE-MAC': this.macAddress,
        'X-APP-VERSION': this.getVersion(),
        'X-OS-NAME': Platform.OS,
        'X-OS-VERSION': Device.getSystemVersion(),
      };
    }
    return this.cacheDeviceInfo;
  }
}
